package com.aaa.tmr.util;

import com.aaa.tmr.entity.Upload;
import com.aaa.tmr.service.UploadService;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author ：Marko
 * @date ：Created in 2021/3/23 22:34
 * @description ：文件上传工具类
 * @modified By：
 * @version:
 */
@Component
public class OssUtil {

    @Resource
    private UploadService uploadService;

    /**
     * description: 文件上传通用方法
     * @param file        上传文件
     * @param savePath    保存路径
     * @param ossProperty 配置参数
     * @return java.lang.String
     * @author Marko
     * @Date 2021/3/23 22:36
     **/
    public String uploadFile(MultipartFile file, String savePath, OssProperty ossProperty) {
        Upload upload = new Upload();
        OSS ossClient = null;
        try {
            //获取原文件名称
            String originalFilename = file.getOriginalFilename();
            //获取原文件后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //拼装新文件名称
            String newfileName = UUID.randomUUID()+suffix;
            //防止savePath不带/  savePath = a/b/c
            if(!savePath.endsWith("/")){
                savePath=savePath+"/";
            }
            //最终新文件全路径为 a/b/c/fdsfdsafasdfadsfawr.png
            String newfilePath = savePath+newfileName;
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(ossProperty.getEndpoint(),
                    ossProperty.getAccessKeyId(),ossProperty.getAccessKeySecret());

            InputStream inputStream = file.getInputStream();
            String url= ossProperty.getUrl();
            // 上传文件到指定的存储空间（bucketName）并将其保存为指定的文件名称（objectName）。
            ossClient.putObject(ossProperty.getBucketName(), newfilePath, inputStream);
            upload.setSourceName(originalFilename);
            upload.setDestinationName(url+newfilePath);
            uploadService.insert(upload);
            return newfilePath;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(ossClient!=null) {
                // 关闭OSSClient。
                ossClient.shutdown();
            }
        }

        return null;
    }
}
